/**
 * @Author: lena
 * @Description:udp服务端
 * @Version: 1.0.0
 * @Date: 2021/9/11 14:27
 */

package udp

import (
	"bufio"
	"fmt"
	"net"
	"os"
)

func Server1() {
	// 监听端口 : func DialUDP(network string, laddr, raddr *UDPAddr) (*UDPConn, error)
	conn, err := net.DialUDP("udp", nil, &net.UDPAddr{
		IP:   net.IPv4(127, 0, 0, 1),
		Port: 20000,
	})
	if err != nil {
		fmt.Println("client listen err :", err)
		return
	}
	defer conn.Close()

	// 收发数据
	var reply [1024]byte
	reader := bufio.NewReader(os.Stdin)
	for {
		// 发送数据
		fmt.Printf("[server]请输入要发送的信息：")
		readString, err := reader.ReadString('\n')
		if err != nil {
			fmt.Println("[server]read input err :", err)
			break
		}
		conn.Write([]byte(readString))
		// 接收信息 => 等待回复
		n, _, err := conn.ReadFromUDP(reply[:])
		if err != nil {
			fmt.Println("[server]receive err :", err)
			break
		}
		fmt.Println("[server]收到信息：", string(reply[:n]))

	}
}
